package com.gem.taskplan.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	public static HttpClient httpClient = new DefaultHttpClient();
	//public static final String BASE_URL = "http://192.168.23.1:8080/joy/";
	//通过get方法发送请求
	public static String getRequest(final String url) throws Exception{
		FutureTask<String> task = new FutureTask<String>(new Callable<String>() {

			@Override
			public String call() throws Exception {
				HttpGet get = new HttpGet(url);
				HttpResponse response =	httpClient.execute(get);
				if(response.getStatusLine().getStatusCode() == 200){
					//加载成功
					String result = EntityUtils.toString(response.getEntity());
					return result;
				}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}
	//通过post方法发送请求
	public static String postRequest(final String url ,final Map<String, String> params) throws Exception{
		FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				HttpPost post = new HttpPost(url);
				List<NameValuePair> param = new ArrayList<NameValuePair>();
				for(String key:params.keySet()){
					//封装请求参数
					param.add(new BasicNameValuePair(key, params.get(key)));
				}
				//设置请求参数
				post.setEntity(new UrlEncodedFormEntity(param,HTTP.UTF_8));
				//发送post请求
			HttpResponse response = httpClient.execute(post);
			if(response.getStatusLine().getStatusCode() == 200){
				//响应成功
				String result = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
				return result;
			}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}
}
